package com.wtx.fitness.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.wtx.fitness.config.OSSConfig;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 阿里云OSS工具类
 */
@Component
public class OSSUtil {

  private final OSSConfig ossConfig;

  public OSSUtil(OSSConfig ossConfig) {
    this.ossConfig = ossConfig;
  }

  /**
   * 上传文件到OSS
   * 
   * @param file 要上传的文件
   * @param dir  OSS中的目录，例如 avatars/student/
   * @return 上传后的文件访问URL
   */
  public String uploadFile(MultipartFile file, String dir) throws IOException {
    // 生成文件名
    String originalFilename = file.getOriginalFilename();
    String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
    String fileName = UUID.randomUUID().toString().replace("-", "") + fileExtension;

    // 生成文件路径
    String dateDir = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
    String fileKey = dir + dateDir + "/" + fileName;

    // 获取文件输入流
    InputStream inputStream = file.getInputStream();

    // 创建OSS客户端
    OSS ossClient = new OSSClientBuilder().build(
        ossConfig.getEndpoint(),
        ossConfig.getAccessKeyId(),
        ossConfig.getAccessKeySecret());

    try {
      // 设置元数据
      ObjectMetadata metadata = new ObjectMetadata();
      metadata.setContentLength(file.getSize());
      metadata.setContentType(file.getContentType());

      // 上传文件
      ossClient.putObject(ossConfig.getBucketName(), fileKey, inputStream, metadata);

      // 返回访问URL
      return ossConfig.getUrlPrefix() + fileKey;
    } finally {
      // 关闭客户端
      ossClient.shutdown();
    }
  }

  /**
   * 上传头像文件到OSS
   * 
   * @param file     头像文件
   * @param userType 用户类型：admin或student
   * @param userId   用户ID
   * @return 上传后的头像URL
   */
  public String uploadAvatar(MultipartFile file, String userType, String userId) throws IOException {
    // 直接使用用户类型作为顶级目录，简化路径结构
    String dir = userType + "/" + userId + "/";
    return uploadFile(file, dir);
  }
}